package com.mingtu.dzpatrol.activity;

import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.MetaDataUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gyf.immersionbar.ImmersionBar;
import com.hikvision.hatomplayer.HatomPlayerSDK;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.adapter.TabbarAdapter;
import com.mingtu.dzpatrol.base.BaseActivity;
import com.mingtu.dzpatrol.base.BaseApplication;
import com.mingtu.dzpatrol.callback.StringDialogCallback;
import com.mingtu.dzpatrol.entity.TabEntity;
import com.mingtu.dzpatrol.fragment.Tab1Fragment;
import com.mingtu.dzpatrol.fragment.Tab2Fragment;
import com.mingtu.dzpatrol.fragment.Tab3Fragment;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.SPTools;
import com.mingtu.dzpatrol.utils.StatusBarUtil;
import com.mingtu.dzpatrol.viewpager.NoScrollViewPager;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {


    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;
    @BindView(R.id.tl)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_top_right)
    ImageView ivTopRight;
    @BindView(R.id.iv_track)
    ImageView ivTrack;
    @BindView(R.id.layout_title)
    RelativeLayout layoutTitle;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private static final String[] mTitles = {"首页", "", "我的"};
    private static final int[] mNormalIcons = {R.mipmap.tab_index_normal, 0, R.mipmap.tab_mine_normal};
    private static final int[] mSeleIcons = {R.mipmap.tab_index_selected, 0, R.mipmap.tab_index_selected};
    private Tab2Fragment tab2Fragment;
    private int navPosition = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        tab2Fragment = new Tab2Fragment();
        mFragments.add(new Tab1Fragment());
        mFragments.add(tab2Fragment);
        mFragments.add(new Tab3Fragment());

        viewPager.setOffscreenPageLimit(mFragments.size());
        viewPager.setAdapter(new TabbarAdapter(getSupportFragmentManager(), mFragments));


        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mSeleIcons[i], mNormalIcons[i]));
        }

        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(onTabSelectListener);
        viewPager.addOnPageChangeListener(onPageChangeListener);
        viewPager.setCurrentItem(navPosition);
    }

    @Override
    protected void initView() {
        hideHeadView();
        setSrlEnableOverScrollDrag(false);
        StatusBarUtil.addStatusBarHeight(statusBarView);
        //沉侵式状态栏
        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(true);  //状态栏字体是深色，不写默认为亮色
        immersionBar.init();

        tvTitle.setText(mTitles[navPosition]);

        layoutTitle.setVisibility(View.GONE);
        statusBarView.setVisibility(View.GONE);
        getCameraConfigInfo();
    }

    @Override
    protected void getData() {
        initPolicyGrant();
    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        try {
            tab2Fragment.setNetWorkState(netWorkState);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private OnTabSelectListener onTabSelectListener = new OnTabSelectListener() {
        @Override
        public void onTabSelect(int position) {
            viewPager.setCurrentItem(position, false);

        }

        @Override
        public void onTabReselect(int position) {

        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            commonTabLayout.setCurrentTab(position);
            tvTitle.setText(mTitles[position]);
            if (position == 1) {
                layoutTitle.setVisibility(View.VISIBLE);
                statusBarView.setVisibility(View.VISIBLE);
                ImmersionBar immersionBar = ImmersionBar.with(MainActivity.this);
                immersionBar.statusBarDarkFont(true);  //状态栏字体是深色，不写默认为亮色
                immersionBar.init();
            } else {
                layoutTitle.setVisibility(View.GONE);
                statusBarView.setVisibility(View.GONE);
                ImmersionBar immersionBar = ImmersionBar.with(MainActivity.this);
                immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
                immersionBar.init();
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    //隐私声明
    private void initPolicyGrant() {
        String appChannel = "mingtu";
        String userName = SPStaticUtils.getString(SPTools.userName);
        if (!StringUtils.isEmpty(userName)) {
            appChannel = userName;
        }

        String baiduStatAppkey = MetaDataUtils.getMetaDataInApp("BaiduMobAd_STAT_ID");
        String buglyAppkey = MetaDataUtils.getMetaDataInApp("com.tencent.bugly.apikey");

        // SDK初始化，该函数不会采集用户个人信息，也不会向百度移动统计后台上报数据
        StatService.init(context, baiduStatAppkey, appChannel);
        // 通过该接口可以控制敏感数据采集，true表示可以采集，false表示不可以采集，
        // 该方法一定要最优先调用，请在StatService.start(this)之前调用，采集这些数据可以帮助App运营人员更好的监控App的使用情况，
        // 建议有用户隐私策略弹窗的App，用户未同意前设置false,同意之后设置true
        StatService.setAuthorizedState(this, true);
        // 自动埋点，建议在Application中调用。否则可能造成部分页面遗漏，无法完整统计。
//        StatService.autoTrace(this, true, true);

        // setSendLogStrategy已经@deprecated，建议使用新的start接口
        // 如果没有页面和自定义事件统计埋点，此代码一定要设置，否则无法完成统计
        // 进程第一次执行此代码，会导致发送上次缓存的统计数据；若无上次缓存数据，则发送空启动日志
        // 由于多进程等可能造成Application多次执行，建议此代码不要埋点在Application中，否则可能造成启动次数偏高
        // 建议此代码埋点在统计路径触发的第一个页面中，若可能存在多个则建议都埋点
        StatService.start(this);

        //bugly
        CrashReport.initCrashReport(getApplicationContext(), buglyAppkey, false);
        CrashReport.setDeviceId(context, DeviceUtils.getUniqueDeviceId()); // 设备id
        CrashReport.setDeviceModel(context, DeviceUtils.getModel()); //设备型号
        CrashReport.setAppVersion(context, AppUtils.getAppVersionName());
        CrashReport.setAppPackage(context, AppUtils.getAppPackageName());
    }


    @OnClick({R.id.iv_top_right, R.id.iv_track})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top_right:
                break;
            case R.id.iv_track:
                layoutTitle.setVisibility(View.VISIBLE);
                statusBarView.setVisibility(View.VISIBLE);
                viewPager.setCurrentItem(1, false);
                tvTitle.setText("资源地图");
                if (!XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) ||
                        !XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
                    new XPopup.Builder(MainActivity.this)
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_location_storage_auth),
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            tab2Fragment.locationPermissions();
                                        }
                                    }, null, false)
                            .show();
                }
                break;
        }
    }

    /**
     * 获取摄像头配置信息
     */
    private void getCameraConfigInfo() {

        OkGo.<String>post(Constant.getInstance().POST_CAMERA_CONFIG_INFO)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body(); //{"msg":"success","code":0,"cameraInfo":"24571460|p765VtI8gnCXlFXAbRLJ|123.7.84.20|1443"}
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals("success")) {
                                String cameraConfigInfo = jsonObject.getString("cameraInfo");
                                String[] info = cameraConfigInfo.split("\\|");// “.”和“|”都是转义字符，必须得加"\\";

                                try {
                                    String appkey = info[0];
                                    String secret = info[1];
                                    String ip = info[2];
                                    String port = info[3];
                                    //海康
                                    HatomPlayerSDK.init(BaseApplication.getBaseApplication(), appkey, true);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                        }
                    }
                });
    }
}
